package com.coocaa.typhoon.api.third.elasticsearch.service;

import com.coocaa.typhoon.api.third.elasticsearch.model.UserFileDoc;
import com.coocaa.typhoon.api.third.elasticsearch.repository.UserFileRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @author bijiahao
 * @date : 2025/10/22 09:15
 * @description
 */
@Service
public class UserFileEsService {
    @Autowired
    private UserFileRepository repository;

    public void save(UserFileDoc entity) {
        if (entity.getCreatedDate() == null) {
            entity.setCreatedDate(LocalDateTime.now());
        }
        entity.setLastUpdateDate(LocalDateTime.now());
        //id存在时更新
        repository.save(entity);
    }

    public void saveAll(List<UserFileDoc> list) {
        list.forEach(e -> {
            e.setCreatedDate(Optional.ofNullable(e.getCreatedDate()).orElse(LocalDateTime.now()));
            e.setLastUpdateDate(LocalDateTime.now());
        });
        repository.saveAll(list);
    }

    /* ---------------- 删 ---------------- */
    public void deleteById(String id) {
        repository.deleteById(id);
    }


    /* ---------------- 查 ---------------- */
    public Optional<UserFileDoc> findById(String id) {
        return repository.findById(id);
    }

    public List<UserFileDoc> findByUserId(String userId) {
        return repository.findByUserId(userId);
    }

    public Page<UserFileDoc> pageByFileType(String fileType, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return repository.findByFileType(fileType, pageable);
    }

    public Page<UserFileDoc> searchFilePath(String key, int page, int size) {
        return repository.searchInFilePath(key, PageRequest.of(page, size));
    }
}
